<script setup lang="ts">
import { useRouter } from 'vue-router';
import {
  changePasswordPost,
  informationGet,
  sendMessagePost,
  updateLoginAccountPost,
} from '@/services/my.ts';
import type { FieldType } from 'vant';
import { logoutPost } from '@/services/login.ts';

const $router = useRouter();
const accountSet = reactive({
  customerName: '',
  account: '',
});
let timer = ref<number | null>(null); // 存储定时器ID
let countdown = ref(0); // 倒计时秒数
const accountRef = ref();
const showAccountPop = ref(false);
const acountPopData = reactive({
  loginPhone: '',
  captcha: '',
});
const accountRules: any = reactive({
  loginPhone: [{ required: true, message: '请输入手机号码' }],
  captcha: [{ required: true, message: '请输入短信验证码' }],
});
const onChangeAccountClick = () => {
  showAccountPop.value = true;
};
const onSendCodeClick = async () => {
  if (!acountPopData.loginPhone) {
    showToast('请输入手机号');
    return;
  }
  // 如果正在倒计时，则不允许再次点击
  if (countdown.value > 0) return;
  const params = { mobile: acountPopData.loginPhone, smsType: 'CHANGE_PHONE' };
  const { message, err } = await sendMessagePost(params);
  if (err) {
    showToast(err);
    return;
  }
  showToast(message);
  countdown.value = 60;
  timer.value = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(timer.value!);
      timer.value = null;
    }
  }, 1000);
};

// 退出登录
const onOutLoginClick = async () => {
  let { err } = await logoutPost();
  if (err) {
    showToast(err);
  } else {
    localStorage.setItem('_mobile_site_token', '');
    $router.push({ path: '/login', replace: true });
  }
};
const onAccountSureClick = async () => {
  try {
    await accountRef.value.validate();
    const { err, message } = await updateLoginAccountPost({
      loginPhone: acountPopData.loginPhone,
      captcha: acountPopData.captcha,
    });
    if (err) {
      showToast(err);
      return;
    }
    showToast(message);
  } catch (error) {
    console.log('error', error);
  }
};

// 修改密码
const passwordShow = ref<FieldType>('password');
const passwordRef = ref();
const showPasswordPop = ref(false);
const passwordPopData = reactive({
  newPassword: '',
  oldPassword: '',
  againPassword: '',
});
const passwordRules = [
  { required: true, message: '请输入密码' },
  {
    validator: (val: any) => /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,15}$/.test(val),
    message: '密码必须包含大小写字母和数字，长度8-15位',
  },
];
const onChangePassword = () => {
  showPasswordPop.value = true;
};
const onPasswordSureClick = async () => {
  try {
    await passwordRef.value.validate();
    const { err, message } = await changePasswordPost({
      newPassword: passwordPopData.newPassword,
      oldPassword: passwordPopData.oldPassword,
    });
    if (err) {
      showToast(err);
      return;
    }
    showToast(message);
  } catch (error) {
    console.log('error', error);
  }
};
const loadData = async () => {
  const { err, data } = await informationGet();
  if (err) {
    showToast(err);
    return;
  }
  accountSet.customerName = data.customerName;
  accountSet.account = data.account;
};

onMounted(() => {
  loadData();
});

// eslint-disable-next-line no-undef
onBeforeUnmount(() => {
  // 组件销毁前清除定时器
  if (timer.value) {
    clearInterval(timer.value);
    timer.value = null;
  }
});
</script>

<template>
  <div class="account-container">
    <van-field v-model="accountSet.customerName" readonly input-align="right" label="企业名称：" />
    <van-field v-model="accountSet.account" readonly input-align="right" label="登录账号" />
    <div class="account-button">
      <van-button @click="onChangeAccountClick" color="#E89000" round block> 更换账号</van-button>
      <van-button @click="onChangePassword" color="#E89000" plain round block> 修改密码</van-button>
      <van-button @click="onOutLoginClick" color="#E89000" plain round block> 退出登录</van-button>
    </div>
  </div>
  <!-- 账号设置 -->
  <van-popup v-model:show="showAccountPop" position="bottom" :style="{ maxHeight: '70%' }">
    <div class="some-pop">
      <div class="pop-title">验证手机号</div>

      <van-form :rules="accountRules" ref="accountRef" required="auto" label-width="7em">
        <van-field
          v-model="acountPopData.loginPhone"
          :rules="accountRules.loginPhone"
          name="loginPhone"
          clearable
          placeholder="请输入手机号码"
        ></van-field>
        <van-field
          :rules="accountRules.captcha"
          v-model="acountPopData.captcha"
          name="captcha"
          clearable
          placeholder="请输入短信验证码"
        >
          <template #button>
            <van-button
              :disabled="countdown > 0"
              @click="onSendCodeClick"
              size="small"
              color="#E89000"
              type="primary"
              plain
            >
              {{ countdown > 0 ? `${countdown}秒后重新获取` : '获取验证码' }}
            </van-button>
          </template>
        </van-field>
        <div class="sure-button">
          <van-button color="#E89000" @click="onAccountSureClick" round block> 确认</van-button>
        </div>
      </van-form>
    </div>
  </van-popup>
  <!-- 修改密码 -->
  <van-popup v-model:show="showPasswordPop" position="bottom" :style="{ maxHeight: '70%' }">
    <div class="some-pop">
      <div class="pop-title">修改密码</div>

      <van-form :rules="accountRules" ref="passwordRef" required="auto" label-width="7em">
        <van-field
          v-model="passwordPopData.oldPassword"
          :type="passwordShow"
          name="password"
          placeholder="请输入原密码"
          :rules="passwordRules"
          @click-right-icon="passwordShow = passwordShow === 'password' ? 'text' : 'password'"
        >
          <template #right-icon>
            <div class="svgIcon">
              <svg-icon :icon-class="passwordShow === 'password' ? 'close' : 'open'" size="1.2em" />
            </div>
          </template>
        </van-field>
        <van-field
          v-model="passwordPopData.newPassword"
          :type="passwordShow"
          :rules="passwordRules"
          name="password"
          placeholder="请输入新密码"
          @click-right-icon="passwordShow = passwordShow === 'password' ? 'text' : 'password'"
        >
          <template #right-icon>
            <div class="svgIcon">
              <svg-icon :icon-class="passwordShow === 'password' ? 'close' : 'open'" size="1.2em" />
            </div>
          </template>
        </van-field>
        <van-field
          v-model="passwordPopData.againPassword"
          :type="passwordShow"
          name="password"
          placeholder="确认新密码"
          :rules="[
            ...passwordRules,
            {
              validator: (val) => val === passwordPopData.newPassword,
              message: '两次输入的密码不一致',
            },
          ]"
          @click-right-icon="passwordShow = passwordShow === 'password' ? 'text' : 'password'"
        >
          <template #right-icon>
            <div class="svgIcon">
              <svg-icon :icon-class="passwordShow === 'password' ? 'close' : 'open'" size="1.2em" />
            </div>
          </template>
        </van-field>
        <div class="sure-button">
          <van-button color="#E89000" @click="onPasswordSureClick" round block> 确认</van-button>
        </div>
      </van-form>
    </div>
  </van-popup>
</template>

<style scoped lang="scss">
.account-container {
  width: 100%;
  min-height: 100vh;

  .account-button {
    width: 100%;
    margin-top: 40px;
    padding: 0 16px;

    .van-button {
      margin: 10px 0;
      height: 40px;
    }
  }
}

.some-pop {
  width: 100%;
  padding: 0 16px;

  .pop-title {
    width: 100%;
    height: 40px;
    font-size: 16px;
    font-weight: 500;
    color: #000000;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .van-cell {
    background: #f6f6f6;
    margin-bottom: 16px;
  }

  .sure-button {
    .van-button {
      margin: 10px 0;
      height: 40px;
    }
  }
}

:deep(.van-field__label) {
  font-size: 14px;
  font-weight: 400;
  color: #000000;
}

:deep(.van-field__control) {
  font-size: 14px;
  font-weight: 400;
  color: #00000080;
}
</style>
